package com.ruoyi.modules.appController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.modules.domain.DyAgentUser;
import com.ruoyi.modules.service.IDyAgentUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 盲盒-用户信息Controller
 *
 * @author ruoyi
 * @date 2021-10-29
 */
@Api(tags = "APP - 用户登录")
@RestController
@RequestMapping("/app/user/login")
@Slf4j
public class AppDyAgentUserLoginController extends BaseController {

    @Autowired
    private IDyAgentUserService dyAgentUserService;
    @Autowired
    private TokenService tokenService;

    /**
     * 根据账号验证码登录
     */
    @ApiOperation(value="根据账号验证码登录", notes="盲盒-根据账号验证码登录")
    @GetMapping(value = "/openApi/loginByPassword")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "账号", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true),
    })
    public AjaxResult loginByPhone(HttpServletRequest req,
                                   @RequestParam(name="username",required=true) String username
                                    , @RequestParam(name="password",required=true) String password) {


        DyAgentUser dyAgentUser = dyAgentUserService.getOne(new LambdaQueryWrapper<DyAgentUser>().eq(DyAgentUser::getUsername, username).last("limit 1"));
        if (dyAgentUser == null){
            return error("账号不存在！");
        }
        if (!dyAgentUser.getPassword().equals(password)){
            return error("密码错误！");
        }

        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(dyAgentUser.getId());

        String token =  tokenService.createToken(loginUser);

        AjaxResult ajax = AjaxResult.success();
        // 生成token
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }



}
